<template>
<div class="app-container">
  <el-page-header @back="goBack" content="视频页面">
  </el-page-header>
  <div style="background-color: #f6f7f8; padding: 10px; border: 1px solid #f6f7f8; border-radius: 10px">
    <el-row>
      <el-col :span="4" v-for="(item, i) in uploadList" :key="i">
        <div          style="border: 1px solid #ffffff; border-radius: 10px; width: 200px; height: 50px; display: flex; align-items: center; justify-content: center; margin: 5px; cursor: pointer; position: relative;"
                      :class="{ 'clicked': item.isClicked, 'unclicked': !item.isClicked }"
                      @click="toggleClick(item, i)">
          <p :style="{ color: item.isClicked ? 'white' : 'black' }">{{ item.videoTitle }}</p>
          <i class="el-icon-delete" style="position: absolute; top: 5px; right: 5px; cursor: pointer;" @click.stop="removeItem(i)"></i>
        </div>
      </el-col>
      <el-col :span="4">
        <el-upload
          multiple
          :action="uploadImgUrl"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          ref="imageUpload"
          :on-remove="handleDelete"
          :show-file-list="false"
          :headers="headers"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview">
          <el-button size="medium"
                     type="primary"
                     style=" width: 200px;
                     height: 50px; margin: 5px;
                     border: 1px solid #ffffff;
                     border-radius: 10px;
                     ">选取文件</el-button>
        </el-upload>
      </el-col>
    </el-row>


  </div>
  <div class = "app-container">
    <!-- 添加或修改课程视频管理对话框 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="width: 500px">
        <el-form-item label="视频标题" prop="videoTitle">
          <el-input v-model="form.videoTitle" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频封面" prop="videoImageurl">
          <ImageUpload :limit="1" v-model="form.videoImageurl" :showIcon="true"></ImageUpload>
        </el-form-item>
        <el-form-item label="排序" prop="videoSort">
          <el-input-number v-model="form.videoSort" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="视频简介" prop="videoText">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入视频简介"
            v-model="form.videoText">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type ="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
  </div>

</div>
</template>

<script>
import {getToken} from "@/utils/auth";
import {isExternal} from "@/utils/validate";
import {reset} from "chalk";
import {listVideo} from "@/api/siyun/video/video"

export default {
  name: 'videolsit',
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 100,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["mp4", "mkv", "avi", "mov", "wmv", "flv", "webm"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      addorupdate: 0,
      courseid:0,
      imageurl:'',
      isViewing:false,
      // 表单参数
      form: {},
      currentRow: null,
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      videolist:[],
      // 表单校验
      rules: {
      },
      index: 0,
    };
  },
  created() {
  // this.form.num = 0;
    this.form = {
      videoId: null,
      videoUrl: null,
      videoImageurl: '',
      videoCourseid: null,
      videoSort: null,
      videoTitle: null,
      videoText: null,
      videoUploadtime: null,
      videoUploaduser: null
    };
    var videolist = this.$store.state.shipin.videolist;
    if (videolist != null && videolist != undefined && videolist != '' ){
      this.videolist = JSON.parse(videolist)
    }
    //修改时获取课程id
    this.courseid = this.$store.state.shipin.videoCourseid
    if (this.courseid != null && this.courseid != '' && this.courseid != 0){
      this.getvideolsit(this.courseid)
      this.addorupdate= 1;
    }
    // setTimeout(()=>{
    //   var at = this.uploadList.at(0);
    //   this.toggleClick(at, 0);
    // },800)
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              if (item.indexOf(this.baseUrl) === -1 && !isExternal(item)) {
                item = { name: this.baseUrl + item, url: this.baseUrl + item };
              } else {
                item = { name: item, url: item };
              }
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    },
    form: {
      handler(newVal, oldVal) {
        if (this.index !== undefined && this.index >= 0 && this.index < this.videolist.length) {
          // 创建一个新的对象，包含所有新的属性，但保留原有的 videoUrl
          const updatedItem = {
            ...this.videolist[this.index],
            ...newVal,
            videoUrl: this.videolist[this.index].videoUrl
          };
          // 使用 Vue.set 更新 videolist 中的对应项
          this.$set(this.videolist, this.index, updatedItem);
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 获取视频累表
    getvideolsit(){
      this.form.videoCourseid = this.courseid
      listVideo(this.form).then(response => {
        response.data.forEach(item => {
          this.uploadList.push({videoTitle: item.videoTitle,url:item.videoUrl,isClicked:false})
        });
        this.videolist = response.data;
      })
    },
    rest(){
      this.form = {
        videoId: null,
        videoUrl: null,
        videoImageurl: null,
        videoCourseid: null,
        videoSort: null,
        videoTitle: null,
        videoText:null,
        videoUploadtime: null,
        videoUploaduser: null
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.$store.commit('shipin/SET_OPEN',true)
      this.$router.go(-1)
    },
    // 视频列表
    submitForm(){
        var s = JSON.stringify(this.videolist);
        this.$store.commit('shipin/SET_VIDEOLIST', s)
        this.$store.commit('shipin/SET_OPEN' ,true)
      this.$store.commit('shipin/SET_ADDORUPDATE',0)
      this.$router.go(-1)
    },
    removeItem(index) {
      this.uploadList.splice(index, 1);
      this.videolist[index].deleteid = 1;
    },
    goBack() {
      this.$store.commit('shipin/SET_VIDEOCOURSEID',0)
      this.$store.commit('shipin/SET_ADDORUPDATE',0)
      this.$store.commit('shipin/SET_OPEN',true)
      this.videolist=[]
      this.uploadList=[]
      this.$router.go(-1);
    },
    toggleClick(item,index) {
      this.index = index;
      // 重置所有 item 的 isClicked 状态
      this.uploadList.forEach(dataItem => {
        dataItem.isClicked = false;
      });
      // 设置当前点击的 item 的 isClicked 状态为 true
      item.isClicked = true;


      var at = this.videolist.at(index);
      this.form.videoId = at.videoId;
      this.form.videoCourseid = at.videoCourseid;
      this.form.videoSort = at.videoSort;
      this.form.videoTitle = at.videoTitle;
      this.form.videoUploadtime = at.videoUploadtime;
      this.form.videoUploaduser = at.videoUploaduser;
      this.form.videoImageurl = at.videoImageurl;
      this.form.videoText = at.videoText;

    },
    //在上一次的基础添加对应的form数据
    // addform(){
    //   var index = this.index;
    //   var videolistElement = this.videolist[index];
    //   console.log(videolistElement.videoCourseid)
    //   if (videolistElement.videoCourseid == 0){
    //     this.videolist[index].videoImageurl = this.form.videoImageurl;
    //     this.videolist[index].videoTitle = this.form.videoTitle;
    //     this.videolist[index].videoUploadtime = this.form.videoUploadtime;
    //     this.videolist[index].videoUploaduser = this.form.videoUploaduser;
    //     this.videolist[index].videoSort = this.form.videoSort;
    //     this.videolist[index].videoText = this.form.videoText;
    //   }else if (videolistElement.videoId != 0){
    //     // this.videolist[index].videoImageurl = this.form.videoImageurl;
    //     // this.videolist[index].videoTitle = this.form.videoTitle;
    //     // this.videolist[index].videoUploadtime = this.form.videoUploadtime;
    //     // this.videolist[index].videoUploaduser = this.form.videoUploaduser;
    //     // this.videolist[index].videoSort = this.form.videoSort;
    //     // this.videolist[index].videoText = this.form.videoText;
    //   }
    // },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确，请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (file.name.includes(',')) {
        this.$modal.msgError('文件名不正确，不能包含英文逗号!');
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ videoTitle: res.originalFilename, url: res.url,isClicked:false });
        this.videolist.push({videoUrl:res.url,videoImageurl:null,videoSort:null,videoTitle:null,videoUploadtime:null,videoUploaduser:null,videoText:null,videoCourseid:0,deleteid:0})
        this.$modal.closeLoading();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>

<style scoped>
.clicked {
  background-color: #00aeec;
  color: white;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.unclicked {
  background-color: white;
  color: black;
  transition: background-color 0.3s ease, color 0.3s ease;
}
</style>
